package backup

import (
	"context"
	"errors"
	apiv1 "gomod.alauda.cn/mysql-mgr-operator/api/v1"
	apiv1a1 "gomod.alauda.cn/mysql-mgr-operator/api/v1alpha1"
	rdsv1 "gomod.alauda.cn/rds-operator/api/v1"
	"satellite/app/option"
	"satellite/pkg/mgrclient"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

var (
	ErrOfInvalidVersion = errors.New("invalid version")
)

type BaseOption struct {
	option.Base
	Version string
}

type Base struct {
	*BaseOption
}

func NewBase(opt *BaseOption) *Base {
	return &Base{BaseOption: opt}
}

func (b *Base) create(obj client.Object) error {
	ctx, cancel := context.WithTimeout(context.Background(), b.Timeout)
	defer cancel()
	return mgrclient.Client().Create(ctx, obj)
}

func (b *Base) update(obj client.Object) error {
	ctx, cancel := context.WithTimeout(context.Background(), b.Timeout)
	defer cancel()
	return mgrclient.Client().Update(ctx, obj)
}

func (b *Base) delete(obj client.Object) error {
	ctx, cancel := context.WithTimeout(context.Background(), b.Timeout)
	defer cancel()
	return mgrclient.Client().Delete(ctx, obj)
}

func (b *Base) getMysqlCr() (*rdsv1.Mysql, error) {
	ctx, cancel := context.WithTimeout(context.Background(), b.Timeout)
	defer cancel()
	return mgrclient.GetMysqlCr(ctx, b.Namespace, b.Name)
}

func (b *Base) getMgrCr() (*apiv1a1.MySQLCluster, error) {
	ctx, cancel := context.WithTimeout(context.Background(), b.Timeout)
	defer cancel()
	return mgrclient.GetMgrCr(ctx, b.Namespace, b.Name)
}

func (b *Base) getBackupCr() (*apiv1.MySQLBackup, error) {
	ctx, cancel := context.WithTimeout(context.Background(), b.Timeout)
	defer cancel()
	return mgrclient.GetBackupCr(ctx, b.Namespace, b.Name)
}
